package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.model.enums.*;

import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.OrderDetailMapper;
import com.atguigu.gmall.payment.mapper.OrderInfoMapper;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.atguigu.gmall.rabbitmq.config.RabbitConst;
import com.atguigu.gmall.rabbitmq.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Auther 赵乾坤
 * @Date 2021-01-11 22:57
 */
@Service
public class PaymentServiceImpl  implements PaymentService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;//因为查询订单表所以注入

    //1：查询支付表
    //2:没有  生成支付表
    //3:有 直接使用之前生成好的支付表就可以了
    @Override
    public PaymentInfo insert(Long orderId) {
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
        .eq("order_id",orderId));
        if (null == paymentInfo) {
            //没有
            paymentInfo = new PaymentInfo();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(PaymentType.ALIPAY.name());
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            paymentInfo.setSubject(orderInfo.getTradeBody());
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.insert(paymentInfo);

        }
        return paymentInfo;
    }

    @Autowired
    private RabbitService rabbitService;

    //支付表更新
    @Override
    @Transactional
    public void updatePaymentInfo(Map<String, String> paramsMap) {
        //1:查询
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("out_trade_no", paramsMap.get("out_trade_no")));
        if (null != paymentInfo && paymentInfo.getPaymentStatus().
                equals(PaymentStatus.UNPAID.name())) {
            //更新
            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
            //流水号
            paymentInfo.setTradeNo(paramsMap.get("trade_no"));
            //回调时间
            paymentInfo.setCallbackTime(new Date());//接收到回调
            //回调内容
           paymentInfo.setCallbackContent(JSONObject.toJSONString(paramsMap));
            paymentInfoMapper.updateById(paymentInfo);
            //MQ 通知订单微服务 更新订单状态
            //同时更新订单状态
            OrderInfo orderInfo = orderInfoMapper.selectById(paymentInfo.getOrderId());
            if (null != orderInfo && orderInfo.getOrderStatus().equals(OrderStatus.UNPAID.name())) {
                orderInfo.setProcessStatus(ProcessStatus.PAID.name());//进度状态
                orderInfo.setOrderStatus(OrderStatus.PAID.name());//订单状态
                orderInfoMapper.updateById(orderInfo);
                //MQ 生产端
                rabbitService.sendMessage(RabbitConst.EXCHANGE_DIRECT_WARE_STOCK,
                        RabbitConst.ROUTING_WARE_STOCK,
                        JSONObject.toJSONString(initWareOrder(orderInfo.getId())));

            }

        }

    }

    //MQ生产端发消息给仓库　构建仓库所有数据
    public Map initWareOrder(Long orderId) {
        OrderInfo orderInfo = getOrderInfo(orderId);
        //1：Map  订单表信息
        //2: List<Map> 订单详情信息
        //3: Map.put("detail",List<Map> );
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderId", orderInfo.getId());
        map.put("consignee", orderInfo.getConsignee());
        map.put("consigneeTel", orderInfo.getConsigneeTel());
        map.put("orderComment", orderInfo.getOrderComment());
        map.put("orderBody", orderInfo.getTradeBody());
        map.put("deliveryAddress", orderInfo.getDeliveryAddress());
        map.put("paymentWay", orderInfo.getPaymentWay().
                equals(PaymentWay.ONLINE.name()) ? "2" : "1");

//        map.put("wareId", orderInfo.getWareId());// 仓库Id ，减库存拆单时需要使用！
    /*
    details:[{skuId:101,skuNum:1,skuName:
    ’小米手64G’},
    {skuId:201,skuNum:1,skuName:’索尼耳机’}]
     */
        ArrayList<Map> mapArrayList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            HashMap<String, Object> orderDetailMap = new HashMap<>();
            orderDetailMap.put("skuId", orderDetail.getSkuId());
            orderDetailMap.put("skuNum", orderDetail.getSkuNum());
            orderDetailMap.put("skuName", orderDetail.getSkuName());
            mapArrayList.add(orderDetailMap);
        }
        map.put("details", mapArrayList);
        return map;
    }

    //查询订单表及详情表
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>()
                .eq("order_id", orderId));
        orderInfo.setOrderDetailList(orderDetailList);
        return  orderInfo;
    }
    @Autowired
    private OrderDetailMapper orderDetailMapper;
}
